package com.miboxlabs.esecure.ui;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.j256.ormlite.dao.Dao;
import com.miboxlabs.esecure.R;
import com.miboxlabs.esecure.data.FolderListAdapter;
import com.miboxlabs.esecure.entity.Folder;
import com.miboxlabs.esecure.provider.DatabaseHelper;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class Home extends Activity {
	private DatabaseHelper databaseHelper = null;
	List<Folder> folderList;
	FolderListAdapter folderListAdapter;
	ListView lvfolderList;
	Button btnAddNewRecord;
	Dao<Folder, Integer> folderDao;
	Folder folder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		initializeControls();
		loadData();
		registerEvents();

	}

	private void registerEvents() {
		// TODO Auto-generated method stub

		btnAddNewRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
					folderDao = getHelper().getFolderDao();
					folder = new Folder();
					folder.setName("New Folder");
					folderDao.create(folder);

					folderList = folderDao.queryForAll();
					folderListAdapter = new FolderListAdapter(Home.this,
							new ArrayList<Folder>(folderList));
					lvfolderList.setAdapter(folderListAdapter);

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
	}

	private void loadData() {
		// TODO Auto-generated method stub

		try {
			folderDao = getHelper().getFolderDao();

			folderList = folderDao.queryForAll();
			folderListAdapter = new FolderListAdapter(this,
					new ArrayList<Folder>(folderList));
			lvfolderList.setAdapter(folderListAdapter);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initializeControls() {
		// TODO Auto-generated method stub
		lvfolderList = (ListView) findViewById(R.id.lvFolderList);
		btnAddNewRecord = (Button) findViewById(R.id.btnAddNewRecord);
	}

	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = DatabaseHelper.getHelper(this);
		}
		return databaseHelper;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (databaseHelper != null) {
			databaseHelper.close();
			databaseHelper = null;
		}
	}

}
